<?php
/**
 * MenuController class is the controller for business portal.
 * 
 * Yawii Business 版权所有 @ 2012.
 */
class MenuController extends Controller
{
	/**
	 * @return array action filters
	 */
	public function filters() {
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}
	
	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules() {
		return array(
			array('allow', // allow authenticated user to perform below actions
				'actions'=>array('index', 'list', 'form', 'view'),
				'users'=>array('@'),
			),
			array('deny',  // deny all users
				'actions'=>array('index', 'list', 'form', 'view'),
				'users'=>array('*'),
			),
		);
	}

	/**
	 * go to the menu list page 
	 */
	public function actionIndex()
	{
		//handle page=?
		$page_size = Yii::app()->params['pageSize'] + 30;
		$current_page = Yii::app()->request->getParam('page', 1);
		$offset = ($current_page - 1) * $page_size;
		$sql_limit = " LIMIT {$offset}, {$page_size} ";
		if (empty($_GET['view'])) {
			$sql_limit = '';
		}
		
		$sql_where = ' AND m.id_merchant=:id_merchant ';
		$params = array('id_merchant'=>(int)Yii::app()->user->id);
		
		//post filter_name
		$filter_name = Yii::app()->request->getPost('filter_name', '');
		if (!empty($filter_name)) {
			$sql_where .= ' AND m.name LIKE :name ';
			$params['name'] = "%{$filter_name}%";
		}
		
		//post filter_status
		$filter_status = Yii::app()->request->getPost('filter_status', '');
		if ($filter_status === '2') {
			$sql_where .= ' AND m.status=2';
		} else if ($filter_status === '1') {
			$sql_where .= ' AND m.status=1';
		} else if ($filter_status === '0') {
			$sql_where .= ' AND (m.status is null OR m.status=0)';
		}
		
		//get view=?
		$view = Yii::app()->request->getQuery('view', null);
		if ($view == 'list') {
			$sql_orderby = ' ORDER BY m.update_timestamp DESC';
		} else {
			$sql_orderby = ' ORDER BY c.name, m.name, m.update_timestamp DESC';
		}
		
		//1. fetch menu
		$sql_menu = 'SELECT m.id, m.id_category, m.number, m.url_picture, m.name, m.description, m.price, m.price_flexible, m.featured, m.status,
			UNIX_TIMESTAMP(m.submitted_time) AS uts_submitted, UNIX_TIMESTAMP(m.published_time) AS uts_published,
			UNIX_TIMESTAMP(m.insert_timestamp) AS uts_insert, UNIX_TIMESTAMP(m.update_timestamp) AS uts_update,
			c.name AS cateogry_name
			FROM tbl_merchant_menu_item m
			LEFT JOIN tbl_merchant_dish_category c ON c.id=m.id_category AND c.id_merchant=m.id_merchant
			WHERE m.trash=0 '
			. $sql_where
			. $sql_orderby
			. $sql_limit;
		$sql_count = 'SELECT COUNT(m.id) AS total FROM tbl_merchant_menu_item m WHERE m.trash=0 ' . $sql_where;
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql_menu);
		$item_rows = $command->queryAll(true, $params);
		$command = $connection->createCommand($sql_count);
		$aTotal = $command->queryRow(true, $params);
		$connection->active = false;
		
		if (Yii::app()->request->isAjaxRequest) {
			if (empty($_GET['view'])) $this->renderPartial('_menu', array('model' => $item_rows));
			else $this->renderPartial('_list', array('model' => $item_rows));
		} else {
			//set pager
			$pages = new CPagination($aTotal['total']);
			$pages->setPageSize($page_size);
			$this->render('index', array('model' => $item_rows, 'pages' => $pages));
		}
	}
	
	public function actionForm($id = null)
	{
		$model = empty($id) ? new DishForm() : $this->_loadModel((int)$id);
		
		// if it is ajax validation request
		if (isset($_POST['ajax']) && $_POST['ajax'] === 'dish-form') {
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
		
		//query all added categories for this merchant
		$sql_category = 'SELECT id, name FROM tbl_merchant_dish_category WHERE id_merchant=:id_merchant ORDER BY name';
		$connection = Yii::app()->db;
		$command = $connection->createCommand($sql_category);
		$rows_categories = $command->queryAll(true, array('id_merchant'=>(int)Yii::app()->user->id));
		$connection->active = false;
		
		// collect user input data
		if (isset($_POST['DishForm'])) {
			$model->attributes = $_POST['DishForm'];
			
			$model->id_merchant = Yii::app()->user->id;
			
			//update
			$model->update_timestamp = new CDbExpression('NOW()');
			
			//set the sensitive code
			if (isset($_POST['sensitive_code']) and count($_POST['sensitive_code']) > 0) {
				$model->sensitive_code = implode(',', $_POST['sensitive_code']);
			}
			
			$post_dish_category = strtolower($_POST['dish_category']);
			if (!empty($post_dish_category)) {
				//find the ID from $rows_categories
				$row_new = array();
				foreach ($rows_categories as $r) {
					if ($post_dish_category == $r['name']) {
						$row_new['id'] = $r['id'];
						$row_new['name'] = $r['name'];
					}
				}
				if (empty($row_new['id'])) {
					//insert selected_dish_category if not exist
					$connection = Yii::app()->db;
					$params = array('id_merchant'=>(int)Yii::app()->user->id, 'name'=>$post_dish_category);
					$command = $connection->createCommand('INSERT INTO tbl_merchant_dish_category (id_merchant, name) VALUES(:id_merchant, :name)');
					$command->execute($params);
					$command = $connection->createCommand('SELECT id, name FROM tbl_merchant_dish_category WHERE id_merchant=:id_merchant AND name=:name');
					$row_new = $command->queryRow(true, $params);
					$connection->active = false;
				}
				$model->id_category = $row_new['id'];
				$selected_category = $row_new['name'];
			}
			
			//if modified, then set it to unsubmitted status (status=0)
			if ($id > 0 and $model->status > 0) {
				$model->status = 0;
			}
			
			//Auto-submit: set the status=1 always
			$model->status = 1;
			
			if ($model->save()) {
				Yii::app()->request->redirect($this->createUrl('/menu/index', array('view'=>'list')));
			} else {
				Yii::app()->user->setFlash('saved', 'System error was happen when you saved!');
				$this->refresh();
			}
		} else {
			//get dish category array (name => name)
			$dish_categories = array();
			$selected_category = '';
			foreach ($rows_categories as $r) {
				$dish_categories[$r['name']] = $r['name'];
				if (!empty($model->id_category)) {
					if ($r['id'] === $model->id_category) {
						$selected_category = $r['name'];
					}
				}
			}
			$this->render('form', array(
				'model' => $model,
				'selected_category' => $selected_category,
				'dish_categories' => $dish_categories,
			));
		}
	}
	
	/**
	 * AJAX publish a special.
	 */
	public function actionSubmit($id) {
		//update status=1, submitted_time=NOW() (only for status=0)
		$connection = Yii::app()->db;
		$command = $connection->createCommand('UPDATE tbl_merchant_menu_item SET status=1, submitted_time=NOW() WHERE id=:id AND id_merchant=:id_merchant AND status=0');
		$command->execute(array('id'=>$id, 'id_merchant'=>Yii::app()->user->id));
		$connection->active = false;
	}
	
	/**
	 * AJAX delete a special.
	 */
	public function actionDelete($id) {
		//delete current menu item (only for status=0)
		$connection = Yii::app()->db;
		$command = $connection->createCommand('UPDATE tbl_merchant_menu_item SET trash=1 WHERE id=:id AND id_merchant=:id_merchant');
		$command->execute(array('id'=>$id, 'id_merchant'=>Yii::app()->user->id));
		$connection->active = false;
	}

	public function actionPreview($id)
	{
		$model = $this->_loadModel((int)$id);
		$this->renderPartial('_preview', array('model' => $model));
	}
	
	/**
	 * Upload dish photo with AJAX 
	 */
	public function actionUploadPicture($id = null)
	{
		//set folder
		$saved_folder = BUtils::GetUploadingFolder(Yii::app()->user->id);
		$url_folder = BUtils::GetUploadingUrl(Yii::app()->user->id);
		
		//set file name
		$prefix = ($id > 0) ? $id : 'new';
		$file_name = 'dish_' . $prefix . '_' . uniqid();
		
		//set options
		$allowedExtensions = array("jpg","jpeg","gif","png");
		$sizeLimit = 8 * 1024 * 1024;
		Yii::import("ext.EAjaxUpload.qqFileUploader");
		$uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
		$result = $uploader->handleUpload($saved_folder, $file_name, true);
		unset($uploader);
		
		//thumb picture
		$thumb = 'thumb_' . $result['filename'];
		
		Yii::import('ext.iwi.Iwi');
		$picture = new Iwi($saved_folder . $result['filename']);
		$picture->adaptive(700, 700);
		$picture->save($saved_folder . $result['filename']);
		$picture->adaptive(200, 200);
		$picture->save($saved_folder . $thumb);
		unset($picture);
		
		if (isset($result['filename'])) {
			if ($id > 0) {
				$sql_picture = 'UPDATE tbl_merchant_menu_item SET url_picture=:url_picture WHERE id=:id AND id_merchant=:id_merchant AND status=0';
				$params = array('id'=>$id, 'id_merchant'=>Yii::app()->user->id, 'url_picture'=>$url_folder . $thumb);
				$connection = Yii::app()->db;
				$command = $connection->createCommand($sql_picture);
				$command->execute($params);
				$connection->active = false;
			}
			$result['url_thumb'] = $url_folder . $thumb;
		} else {
			$result['error'] = BUtils::T('upload_picture_failed_msg');
		}
		
		echo htmlspecialchars(json_encode($result), ENT_NOQUOTES);
	}
	
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	protected function _loadModel($id)
	{
		$model = DishForm::model()->findByPk(
			$id,
			'id_merchant=:id_merchant AND trash=0',
			array('id_merchant'=>Yii::app()->user->id)
		);
		if ($model === null)
			throw new CHttpException(404, 'The requested page does not exist.');
		return $model;
	}
}